package com.bjsxt;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Iterator;
import java.util.List;

/**
 * 使用DOM4J解析XML
 */
public class TestDom4j1 {
    public static void main(String[] args) throws DocumentException {
        //1.根据XML文档创建DOM4J树
        SAXReader reader = new SAXReader();
        //DOMReader reader = new DOMReader();
        File file = new File("java_xml/student2.xml");
        Document doc = reader.read(file);

        //Document doc = new SAXReader().read(new File("java_xml/student2.xml"));
        //2.获取DOM4J树的根节点students
        Element rootElem = doc.getRootElement();
        //System.out.println(rootElem);
        //3.获取students的子节点student
        //List<Element> stuList =  rootElem.elements("student");
        //Iterator<Element> it = stuList.iterator();
        Iterator<Element> it = rootElem.elementIterator("student");
        //4.对student的属性和子节点进行解析
        while(it.hasNext()){
            //4.1获取每个学生
            Element stuElem = it.next();
            //4.2获取学生的属性
            //Attribute idAttr = stuElem.attribute("id");
            //System.out.println(idAttr.getName()+"---->"+idAttr.getValue());
            Iterator<Attribute> it2 = stuElem.attributeIterator();
            while(it2.hasNext()){
                Attribute attr = it2.next();
                System.out.println(attr.getName()+":"+attr.getValue());
            }
            //4.3 获取student的子元素
            List<Element> nasList = stuElem.elements();
            for(Element elem : nasList){
                //System.out.println(elem.getName()+"--->"+elem.getStringValue());
                System.out.println(elem.getName()+"--->"+elem.getText());
            }
            System.out.println();
        }


    }
}
